﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http.Extensions;
using Microsoft.AspNetCore.Mvc;
using MiniFox.Configurations;
using MiniFox.Resources;
using MiniFox.Web.Configurations;
using System.ComponentModel.DataAnnotations;

namespace MiniFox.Web.Infrastructure
{
    /// <summary>
    /// 通过自动匹配user agent 实现跳转
    /// </summary>
    [AllowAnonymous, NoCache]
    public class ViaController : MvcControllerBase
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        [HttpGet]
        public ActionResult Dispatch([Bind(Prefix = "name"), Required(ErrorMessageResourceType = typeof(CommonMessages), ErrorMessageResourceName = "MSG_CommonRequired")] string name)
        {
            WebConfiguration webConfiguration = ConfigurationFactory.GetConfig<WebConfiguration>();
            var viaAgent = webConfiguration.ViaAgents[name];
            var userAgent = Request.Headers.UserAgent.ToString().ToLower();
            var urlMappings = viaAgent.UrlMappings;

            string url = null;
            foreach (var kv in urlMappings)
            {
                var key = kv.Key;
                if (userAgent.Contains(key.ToLower()))
                {
                    url = kv.Value;
                    break;
                }
            }
            if (string.IsNullOrEmpty(url))
            {
                url = viaAgent.DefaultUrl;
            }

            url = WebUtil.BuildFullUrl(Request.GetFullHost(), Url.Content(url), Request.Query, Request.GetEncodedUrl().GetHash());

            return this.Redirect(url);
        }
    }
}
